/******
 * Javascript library for irods plugin acl data
 *
 * Author: Mike Conway - RENCI (www.renci.org)
 * Date: 07/23/2009
 */



/************************
 * Query irods to get options that match the type of search. This is used to build auto-complete based on dynamic searches of the data.
 *
 * parms:
 * 	searchType - string containing the type of search to do (user, coll, or data)
 *  searchNode - the DOM node that represents the input box that will have auto-completion enabled
 */
function buildAclOptions(searchType, searchNode) {
	try {
		var searchResults = new Array();
		var searchValue = searchNode[0].value;
		console.log("search term for acl:" + searchValue);
		if (searchType == 'user') {
			$.get("irods.xml?_uri=//com.enginframe.irods.domain/get_users_by_user_name&searchUserName=" + searchValue,
						function(data) {
							buildAclAutocompleteWithData(data, searchNode[0]);
						}
						, "text");
		} else if (searchType == "coll") {
			$.get("irods.xml?_uri=//com.enginframe.irods.domain/get_colls_by_coll_name&searchCollName=" + searchValue,
					function(data) {
						buildAclAutocompleteWithData(data, searchNode[0]);
					}
					, "text");
		} else if (searchType == "data") {
			$.get("irods.xml?_uri=//com.enginframe.irods.domain/get_data_objects_by_data_name&searchDataName=" + searchValue,
					function(data) {
						buildAclAutocompleteWithData(data, searchNode[0]);
					}
					, "text");
		} else {
			throw "invalid search type for acl options";
		}
	} catch (err) {
		console.trace();
		console.log("error in initMetaDataSubjectAutocomplete:" + err);
	}
}

/*********************
 * AJAX callback method that processes the reults of the buildAclOptions(searchType, searchNode) method.  Takes the
 * data from the iRODS query and updates the autocomplete options
 * @param data - | delimited data returned from iRODS
 * @param searchNode - DOM node that will have autocompletion updated
 * @return null
 */

function buildAclAutocompleteWithData(data, searchNode) {
	// rebuild the autocomplete array with the incoming data
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
		//console.trace();
		console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 
	

	var serviceData = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
	var autoArray = serviceData.split("|");
	// $(searchNode).autocomplete(autoArray, { minChars:3, autoFill:true, cacheLength:4}).focus();
	$(searchNode).autocomplete(autoArray).focus();
}

/*****
 * Create service query to retrieve ACL data based on search type (user, coll, data), given the search text.  Note that this asynch call
 * will use a callback to process the results of the query (buildAclListFromData(data)).
 *
 * @param searchType - string that switches search type (user, coll, data)
 * @param searchText - search term passed to the iRODS query
 * @return null
 */
function buildAclResultsTable(searchType, searchText) {

	// check for proper parms
	if (searchType == null || searchText == null) {
		throw "invocation exception, null parameters passed";
	}

	$("#aclResult")
	.html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching data from iRODS, please wait...");

	// query irods, doing a search based on the selected search type
	if (searchType == "user") {
		$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_acl_list_by_user_name&_userName=" + searchText, function(data) { buildAclListFromData(data)}, "text");
	} else if (searchType == "coll") {
		$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_acl_list_by_coll_name&_collName=" + searchText, function(data) { buildAclListFromData(data)}, "text");
	} else if (searchType == "data") {
		$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_acl_list_by_data_name&_dataName=" + searchText, function(data) { buildAclListFromData(data)}, "text");
	} else {
		throw "invalid search type for ACL query:" + searchText;
	}
}


function buildAclListFromData(data) {

	
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
		//console.trace();
		console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 
	
	var output = "";

	var coreData = data.substring((data.indexOf("##START##") + 9),
			data.indexOf("##END##"));
	var items = coreData.split("\n");

	output += "<div id='aclDataTableContainer'><table id='aclDataTable'><thead>";
	output += "<tr class='tabd-header'>";
	output += "<th class='tabd-header-field'>User name</th>";
	output += "<th class='tabd-header-field'>Data name</th>";
	output += "<th class='tabd-header-field'>Collection name</th>";
	output += "<th class='tabd-header-field'>Data access type</th>";
	output += "<th class='tabd-header-field'>Data access name</th>";

	output += "</tr></thead><tbody>";

	var expandDiv = "";

	for ( var i = 0; i < (items.length); i++) {
		var tokens = items[i].split("|");

		if (tokens.length > 1) {

			output += "<tr class='tabd-row'>";
			output += "<td class='tabd-field'>"
					+ tokens[0] + "</td>";
			output += "<td class='tabd-field'>" + tokens[2]
					+ "</td>";
			output += "<td class='tabd-field'>" + tokens[4]
			       + "</td>";
			output += "<td class='tabd-field'>" + tokens[5]
			       + "</td>";
			output += "<td class='tabd-field'>" + tokens[6]
			       + "</td></tr>";

		}
	}

		output += "</tbody></table></div>";
		$("#aclResult").html(output);
		dataTab = $("#aclDataTable").dataTable( {
			"bAutoWidth" :true,
			"bSortClasses" :true,
			// TODO: table expansion code temporarily removed - mcc
		//	"aoColumns": [
		//	  			{ "bSortable": false },
		//	  			null, null, null, null,
		//	  		],
				"aaSorting": [[1, 'asc']],
			oLanguage : {
				"sSearch" :"Filter:"
			}
		});

}

